<?php
namespace app\common\model;
// 订单 处理业务
use app\common\model\OrderDetail;
use app\common\service\ServiceAdmin;
use app\common\service\Wechat;
use Firebase\JWT\JWT as JWTUtil;
use plug\SHttp;
use plug\SUtil;
use think\Db;
use think\Exception;
use think\facade\Config;
use think\facade\Env;
use think\facade\Log;
use wxzhifu\example\JsApiPay;
use wxzhifu\example\WxPayConfig;
use wxzhifu\lib\WxPayApi;
use wxzhifu\lib\WxPayUnifiedOrder;

class Order extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_order';
    // 主键ID
    protected $pk = 'order_id';

	//订单状态
	public static $statelist = [
        '2'=>'待配送',
        '3'=>'进行中',
        '4'=>'已完成',
        '6'=>'申请退款',
        '7'=>'订单退款',
	];
	//支付状态
	public static $paystatelist = [
		'1' => '待支付',
		'2' => '已支付',
		'3' => '已取消',
	];
	//特殊订单状态
	public static $specialstatuslist = [
		'1' => '正常',
		'2' => '逃单',
		'3' => '线下付款',
	];
	//兑换领取状态
	public static $receivelist = [
		'1' => '未兑换',
		'2' => '已兑换',
	];
    //性别类型
    public static $sexlist = [
        '1' => '先生',
        '2' => '女士',
    ];

	/**
	 * @param array $where  // 查询的条件
	 * @param string $item  // 查询的参数
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function getOne($where=[1], $item='*')
    {
        $rs = $this
            ->field($item)
            ->where($where)
            ->find();

        return $rs;
    }

    //新增、编辑(后台操作)
    function edit($params, $id=0){
        if($id>0){
            // 更新条件
            $where = ["{$this->pk}" => $id];
            $rs = $this->allowField(true)->save($params, $where);
        }else{
            // 更新数据
            $params['add_time'] = time();
            $rs = $this->save($params);
//            $rs = $this->{$this->pk};
        }
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }

    function getJoinOrder($where=[1], $item='*',$join = [['ddt_shops s','o.shop_id = s.shop_id']])
    {
        $rs = $this
            ->alias('o')
            ->join($join)
            ->field($item)
            ->where($where)
            ->find();

        return $rs;
    }

	function shops_order_list($cond,$orderby,$limit,$is_page = true,$ofield = ['o.*','s.shop_name','u.user_id','u.nick_name'],$dfield = ['*'])
	{
		$where = [];

		if(!empty($cond['shop_name'])){
			$where[] = ['s.shop_name','like','%'.$cond['shop_name'].'%'];
		}
		if(!empty($cond['shop_id'])){
			$where[] = ['o.shop_id','=',$cond['shop_id']];
		}
		if(!empty($cond['user_id'])){
			$where[] = ['o.user_id','=',$cond['user_id']];
		}
		if(!empty($cond['pay_status'])){
			$where[] = ['o.pay_status','=',$cond['pay_status']];
		}
		if(!empty($cond['order_status'])){
			$where[] = ['o.order_status','=',$cond['order_status']];
		}
		if(!empty($cond['order_type'])){
			$where[] = ['o.order_type','=',$cond['order_type']];
		}
		if(!empty($cond['class_ids'])){
			$where[] = ['o.order_type','in',$cond['class_ids']];
		}
		if(isset($cond['is_comment'])){
			$where[] = ['o.is_comment','in',$cond['is_comment']];
		}
		if(!empty($cond['time'])){
			$array = explode(' - ',input('get.time'));
			$start = strtotime($array[0]." 00:00:00");
			if($array[0] == $array[1]){
				$end = strtotime($array[0]." 23:59:59");
			} else {
				$end = strtotime($array[1]." 00:00:00");
			}
			$where[] = ['o.order_time','between',[$start,$end]];
		}

		$jion = [
			['ddt_shops s','o.shop_id = s.shop_id'],
			['ddt_user u','o.user_id = u.user_id'],
		];
        $OrderDetailModel = new OrderDetail();
		if(!empty($cond['product_name'])){
            $orderids = $OrderDetailModel
                ->where('user_id','=',$cond['user_id'])
                ->where('product_name','like','%'.$cond['product_name'].'%')
                ->distinct(true)
                ->column('order_id');
            $where[] = ['o.order_id','in',implode(',',$orderids)];
        }


		$data = $this
			->alias('o')
			->field($ofield)
			->where($where)
			->leftjoin($jion)
			->order($orderby)
			->paginate($limit);
//        echo $this->getLastSql();die;
		if($is_page){
			$page = $data->render();
		}else{
			$page = [
				"total"=> $data->total(),
				"per_page"=> $data->listRows(),
				"current_page"=> $data->currentPage(),
				"last_page"=> $data->lastPage(),
			];
		}

		//处理一个主订单表对应多订单详情表逻辑
		if($data->toArray()){
			$data = $data->toArray()['data'];
			$lists = array_column($data,null,'order_id');
			$order_ids = implode(',',array_column($data,'order_id'));
			$DetailList = $OrderDetailModel->field($dfield)->where([
				['order_id','in',$order_ids]
			])->select()->toArray();
			foreach($DetailList as $key => $value){
			    $lists[$value['order_id']]['number'] = $lists[$value['order_id']]['number']??0 + $value['quantity'];
				$lists[$value['order_id']]['children'][] = $value;
			}
			$data = array_values($lists);
		}
		return ['data'=>$data,'page'=>$page];
	}

	function loveandteam_order_list($cond,$orderby,$limit,$is_page = true,$ofield = ['o.*','s.shop_name','u.user_id','u.nick_name'],$dfield = ['*'])
	{
		$where = [];

		if(!empty($cond['shop_name'])){
			$where[] = ['s.shop_name','like','%'.$cond['shop_name'].'%'];
		}
		if(!empty($cond['shop_id'])){
			$where[] = ['o.shop_id','=',$cond['shop_id']];
		}
		if(!empty($cond['user_id'])){
			$where[] = ['o.user_id','=',$cond['user_id']];
		}
		if(!empty($cond['pay_status'])){
			$where[] = ['o.pay_status','=',$cond['pay_status']];
		}
		if(!empty($cond['order_status'])){
			$where[] = ['o.order_status','=',$cond['order_status']];
		}
		if(!empty($cond['order_type'])){
			$where[] = ['o.order_type','=',$cond['order_type']];
		}
		if(!empty($cond['is_use'])){
			$where[] = ['gr.status','=',$cond['is_use']];
		}
		if(!empty($cond['is_del'])){
			$where[] = ['o.is_del','=',$cond['is_del']];
		}
        if(!empty($cond['class_id'])){
            $where[] = ['o.order_type','=',$cond['class_id']];
        }
        if(!empty($cond['access_code'])){
            $where[] = ['gr.access_code','=',$cond['access_code']];
        }
        if(isset($cond['is_comment'])){
            $where[] = ['o.is_comment','=',$cond['is_comment']];
        }
		if(!empty($cond['time'])){
			$array = explode(' - ',input('get.time'));
			$start = strtotime($array[0]." 00:00:00");
			if($array[0] == $array[1]){
				$end = strtotime($array[0]." 23:59:59");
			} else {
				$end = strtotime($array[1]." 00:00:00");
			}
			$where[] = ['o.order_time','between',[$start,$end]];
		}

		$jion = [
		    ['ddt_goods_record gr','o.order_id = gr.order_id'],
			['ddt_shops s','o.shop_id = s.shop_id'],
			['ddt_user u','o.user_id = u.user_id'],
		];
        $OrderDetailModel = new OrderDetail();
        if(!empty($cond['product_name'])){
            $orderids = $OrderDetailModel
                ->where('user_id','=',$cond['user_id'])
                ->where('product_name','like','%'.$cond['product_name'].'%')
                ->distinct(true)
                ->column('order_id');
            $where[] = ['o.order_id','in',implode(',',$orderids)];
        }
        $afterModel = new Aftersales();
        $reserveModel = new Reserveorder();
		$data = $this
			->alias('o')
			->field($ofield)
			->where($where)
			->leftjoin($jion)
			->order($orderby)
			->paginate($limit)
            ->each(function($item) use($afterModel,$reserveModel){
                $after_sale = $afterModel->where('order_id','=',$item['order_id'])->where('is_show','=',1)->find();
                $item['is_after_sale'] = 2;
                if($after_sale){
                    $item['is_after_sale'] = 1;
                }
                $item['is_can_revocation'] = true;
                if($after_sale['a_s_type'] == 2 && $after_sale['is_refund'] == 2){
                    $item['is_can_revocation'] = false;
                }
                if($item['order_type'] == 4){
                    $reserveinfo = $reserveModel->where('order_id','=',$item['order_id'])->find();
                    $item['reserve_info'] = $reserveinfo;
                }
                return $item;
            });
//        echo $this->getLastSql();die;
		if($is_page){
			$page = $data->render();
		}else{
			$page = [
				"total"=> $data->total(),
				"per_page"=> $data->listRows(),
				"current_page"=> $data->currentPage(),
				"last_page"=> $data->lastPage(),
			];
		}

		//处理一个主订单表对应多订单详情表逻辑
		if($data->toArray()){
			$data = $data->toArray()['data'];
			$lists = array_column($data,null,'order_id');
			$order_ids = implode(',',array_column($data,'order_id'));
			$DetailList = $OrderDetailModel->field($dfield)->where([
				['order_id','in',$order_ids]
			])->select()->toArray();
			foreach($DetailList as $key => $value){
			    $lists[$value['order_id']]['number'] = $lists[$value['order_id']]['number']??0 + $value['quantity'];
				$lists[$value['order_id']]['children'][] = $value;
			}
			$data = array_values($lists);
		}
		return ['data'=>$data,'page'=>$page];
	}

    function get_list($cond, $orderby, $item)
    {

        $where = null;

        if(!empty($cond['user_id'])){
            $where[] = ['user_id','=', $cond['user_id']];
        }
        if(!empty($cond['payment_id'])){
            $where[] = ['payments_id','=', $cond['payment_id']];
        }

        if(!empty($cond['utype'])){
            $where[] = ['utype', '=', $cond['utype']];
        }
        if(!empty($cond['type'])){
            $where[] = ['type', '=', $cond['type']];
        }
        if(!empty($cond['spf_id'])){
            $where[] = ['spf_id', '=', $cond['spf_id']];
        }

        if(!empty($cond['shopid'])){
            $where[] = ['shopid', '=', $cond['shopid']];
        }

        if(!empty($cond['state'])){
            $where[] = ['state', '=', $cond['state']];
        }

        $rs = Db::table($this->table)
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->select();
        return $rs;
    }

    //  商家获取订单详情
    function shops_order_details($orderId, $field="od.*,")
    {
        $rs = Db::table('ddt_orderdetail')
            ->alias('od')
            ->leftJoin('ddt_products p','p.product_id = od.product_id')
            ->leftJoin('ddt_products_type pt','pt.type_id = p.type_id')
//            ->join('ddt_products_stock ps','od.p_s_id = ps.p_s_id')
            ->field($field.'pt.type_name')
            ->where('order_id',$orderId)
            ->select();

        return $rs;
    }

    //  接口获取订单详情
    function api_order_details($orderId,$item = 'od.*',$join = [['ddt_order o','od.order_id = o.order_id'],['ddt_shops s','o.shop_id = s.shop_id']])
    {
        $detailModel = new \app\common\model\OrderDetail();
        $rs = $detailModel
            ->alias('od')
            ->leftJoin($join)
            ->field($item)
            ->where('od.order_id',$orderId)
            ->select()->toArray();
        return $rs;
    }

    //  获取非手动自定义订单详情
    function api_order_details2($orderId,$item = 'od.*',$join = [['ddt_order o','od.order_id = o.order_id'],['ddt_shops s','o.shop_id = s.shop_id']])
    {
        $detailModel = new \app\common\model\OrderDetail();
        $rs = $detailModel
            ->alias('od')
            ->leftJoin($join)
            ->field($item)
            ->where('od.order_id',$orderId)
            ->where('od.p_s_id','<>',0)
            ->select()->toArray();
        return $rs;
    }

////    获取线下订单列表
//    function GetOfflineOrderList($cond,$item = '*',$orderby = 'order_id desc',$limit = 10){
//
//        if(!empty($cond['user_id'])){
//            $where[] = ['user_id','=', $cond['user_id']];
//        }
//        if(isset($cond['shop_id'])){
//            $where[] = ['shop_id','=', $cond['shop_id']];
//        }
//        if(!empty($cond['order_id'])){
//            $where[] = ['order_id','=', $cond['order_id']];
//        }
//
//        if(!empty($cond['order_type'])){
//            $where[] = ['order_type', 'in', $cond['order_type']];
//        }
//        if(!empty($cond['status'])){
//            $where[] = ['order_status', '=', $cond['status']];
//        }
//        $where[] = ['is_del','=',1];
//        $with = [
//            'getShops' => function($query) {
//                $query->field('shop_id,shop_name,shop_phone,address,province,city,area,imagesurl,kefu_image');
//            },
//            'orderDetails',
//            'offlineRecords' => function($query) {
//                $query->field('off_r_id,order_id,seat_id,access_code,seat_info');
//            }
//        ];
//
//        $data = $this
//            ->field($item)
//            ->with($with)
//            ->where($where)
//            ->order($orderby)
//            ->paginate($limit)
//            ->each(function($query){
//                if(!empty($query['offline_records'])){
//                    $query['offline_records']['seat_info'] = json_decode($query['offline_records']['seat_info'],true);
//                }
//                if(!empty($query['order_details'])){
//                    $numbers = array_column($query['order_details']->toArray(),'quantity');
//                    $query['total'] = array_sum($numbers);
//                }
//                return $query;
//            })->toArray();
////        echo $this->getLastSql();
////        var_dump($data);die;
//        return $data;
//    }

//    获取线下订单列表
    function GetOfflineOrderList($cond,$item = '*',$orderby = 'order_id desc',$limit = 10){

        if(!empty($cond['user_id'])){
            $where[] = ['user_id','=', $cond['user_id']];
        }
        if(isset($cond['shop_id'])){
            $where[] = ['shop_id','=', $cond['shop_id']];
        }
        if(!empty($cond['order_id'])){
            $where[] = ['order_id','=', $cond['order_id']];
        }

        if(!empty($cond['order_type'])){
            $where[] = ['order_type', 'in', $cond['order_type']];
        }
        if(!empty($cond['order_status'])){
            $where[] = ['order_status', 'in', $cond['order_status']];
        }
        if(!empty($cond['status'])){
            $where[] = ['order_status', '=', $cond['status']];
        }
        $where[] = ['is_del','=',1];
        $with = [
            'getShops' => function($query) {
                $query->field('shop_id,shop_name,shop_phone,address,province,city,area,imagesurl,kefu_image');
            },
            'orderDetails',
        ];

        $data = $this
            ->field($item)
            ->with($with)
            ->where($where)
            ->order($orderby)
//            ->paginate($limit)
            ->select($limit)
            ->each(function($query){
                if(!empty($query['order_details'])){
                    $numbers = array_column($query['order_details']->toArray(),'quantity');
                    $query['total'] = array_sum($numbers);
                }
                return $query;
            })->toArray();
//        echo $this->getLastSql();
//        var_dump($data);die;
        return $data;
    }

////    获取线下订单详情
//    function GetOfflineOrderInfo($cond,$item = '*'){
//
//        if(!empty($cond['user_id'])){
//            $where[] = ['user_id','=', $cond['user_id']];
//        }
//        if(isset($cond['shop_id'])){
//            $where[] = ['shop_id','=', $cond['shop_id']];
//        }
//        if(!empty($cond['order_id'])){
//            $where[] = ['order_id','=', $cond['order_id']];
//        }
//
//        if(!empty($cond['order_type'])){
//            $where[] = ['order_type', 'in', $cond['order_type']];
//        }
//        if(!empty($cond['state'])){
//            $where[] = ['state', '=', $cond['state']];
//        }
//        $where[] = ['is_del','=',1];
//        $with = [
//            'getShops' => function($query) {
//                $query->field('shop_id,shop_name,shop_phone,address,province,city,area,imagesurl');
//            },
//            'orderDetails',
//            'offlineRecords' => function($query) {
//                $query->field('off_r_id,order_id,seat_id,access_code,seat_info');
//            }
//        ];
//
//        $data = $this
//            ->field($item)
//            ->with($with)
//            ->where($where)
//            ->find();
//        if(!empty($data)){
//            if(!empty($data['offline_records'])){
//                $data['offline_records']['seat_info'] = json_decode($data['offline_records']['seat_info'],true);
//            }
//            if(!empty($data['order_details'])){
//                $numbers = array_column($data['order_details']->toArray(),'quantity');
//                $data['total'] = array_sum($numbers);
//            }
//        }
////        echo $this->getLastSql();
////        var_dump($data);die;
//        return $data;
//    }

//    获取线下订单详情
    function GetOfflineOrderInfo($cond,$item = '*'){

        if(!empty($cond['user_id'])){
            $where[] = ['user_id','=', $cond['user_id']];
        }
        if(isset($cond['shop_id'])){
            $where[] = ['shop_id','=', $cond['shop_id']];
        }
        if(!empty($cond['order_id'])){
            $where[] = ['order_id','=', $cond['order_id']];
        }

        if(!empty($cond['order_type'])){
            $where[] = ['order_type', 'in', $cond['order_type']];
        }
        if(!empty($cond['state'])){
            $where[] = ['state', '=', $cond['state']];
        }
        $where[] = ['is_del','=',1];
        $with = [
            'getShops' => function($query) {
                $query->field('shop_id,shop_name,shop_phone,address,province,city,area,imagesurl,kefu_image');
            },
            'orderDetails'
        ];

        $data = $this
            ->field($item)
            ->with($with)
            ->where($where)
            ->find();
        if(!empty($data)){
            if(!empty($data['order_details'])){
                $numbers = array_column($data['order_details']->toArray(),'quantity');
                $data['total'] = array_sum($numbers);
            }
        }
//        echo $this->getLastSql();
//        var_dump($data);die;
        return $data;
    }

    /**
     * 关联建立和shops的关联
     * hasMany方法的参数包括:hasMany('关联模型名','外键名','主键名',['模型别名定义']);
     */
    public function getShops(){
        return $this->hasOne('Shops',"shop_id","shop_id");
    }

    /**
     * 关联建立和offlinerecord的关联
     * hasMany方法的参数包括:hasOne('关联模型名','外键名','主键名',['模型别名定义']);
     */
    public function offlineRecords(){
        return $this->hasOne('OfflineRecord',"order_id");
    }

    /**
     * 关联建立和OrderDetail的关联
     * hasMany方法的参数包括:hasMany('关联模型名','外键名','主键名',['模型别名定义']);
     */
    public function orderDetails(){
        return $this->hasMany('OrderDetail','order_id');
    }

    /**
     * 关联建立和AfterSales的关联
     * hasMany方法的参数包括:hasMany('关联模型名','外键名','主键名',['模型别名定义']);
     */
    public function AfterSales(){
        return $this->hasMany('Aftersales','order_id');
    }

	// 商铺报表
    function ShopsReportFormList($get,$limit)
    {
        $shopModel = new Shops();

//        $cond['approved'] = 1;
//        $cond['state'] = 1;
//        $cond['shop_name'] = $get['shop_name'];
//        $cond['shop_id'] = $get['shop_id'];

        $where = [
            ['approved', '=', 1],
            ['state', '=', 1],
        ];
        if(!empty($get['shop_name'])){
            $where[] = ['shop_name','like',"%".$get['shop_name']."%"];
        }
        if(!empty($get['shop_type'])){
            $where[] = ['shop_type','=',$get['shop_type']];
        }

        if(!empty($get['shop_id'])){
            $where[] = ['shop_id', '=',$get['shop_id']];
        }
        $timewhere = '';
        if(!empty($get['time'])){
            $array = explode(' - ',input('get.time'));
            $start = strtotime($array[0]);
            if($array[0] == $array[1]){
                $end = strtotime($array[0]." 23:59:59");
            } else {
                $end = strtotime($array[1]);
            }
//            $timewhere = ['order_time','between',[$start,$end]];
            $timewhere = ['pay_time','between',[$start,$end]];
        }

		$field = "shop_id,shop_name,shop_type,province,city,area,address,shop_manager";
        // 分页循环添加数据  （十一）
        $rs = $shopModel->where($where)->field($field)->order('add_time desc')->paginate($limit)->each(function ($item, $key) use($timewhere){
            $shopwhere = [
                ['shop_id','=', $item['shop_id']],
                ['order_status', 'in', '2,3,4'],
                ['pay_status', '=', 2],
                ['order_type', 'in', '4,5'],
                ['special_status','=',1],
                ['is_del','=',1],
            ];
            if(!empty($timewhere)){
                $shopwhere[] = $timewhere;
            }
//            echo "<pre>";
//            var_dump($shopwhere);
			$srt = "(SELECT sum(pay_amount) FROM ddt_order WHERE shop_id = {$item['shop_id']} AND `order_status` IN (2,3,4)  AND `pay_status` = 2 AND `special_status` = 1 AND `is_del` = 1 ";
            if(!empty($timewhere)){
                $srt.= "AND {$timewhere[0]} {$timewhere[1]} {$timewhere[2][0]} AND {$timewhere[2][1]} ";
            }
			//团餐
			$tcfield = $srt."AND order_type = 4) as tc";
			//线下点餐
			$xxdcfield = $srt."AND order_type = 5) as xxdc";
            $rs = $this->where($shopwhere)->field("sum(pay_amount) as money,count(order_id) as count,{$tcfield},{$xxdcfield}")->select()->toArray()[0];
            $item['count'] = $rs['count'];
			$item['money'] = $rs['money'];
			$item['tc'] = $rs['tc'];
			$item['xxdc'] = $rs['xxdc'];
        });
        return $rs;
    }

//    处理订单插入数据
    function placecreateorder($user,$ids,$products,$settlemnt,$address,$receive_id = 0,$order_type = 1){
//        var_dump($products);die;
		$coupon['discount'] = 0.00;
        if($receive_id){
            $CouponReceiveModel = new CouponReceive();
            $coupon = $CouponReceiveModel->where(['receive_id'=>$receive_id,'user_id'=>$user['user_id'],'is_use'=>1])->find()->toArray();
        }

		$newshoplist = [];
        $utype = $user['utype'] == 2 ?'mprice':'sprice';
		foreach($products as $key => $value){
            $newshoplist[$value['shop_id']]['product'][] = $value;
//            $newshoplist[$value['shop_id']]['products_amount'] += calculate([$value[$utype],$value['quantity']],'*');
            if(isset($newshoplist[$value['shop_id']]['products_amount'])){
                $newshoplist[$value['shop_id']]['products_amount'] += calculate([$value[$utype],$value['quantity']],'*');
            } else {
                $newshoplist[$value['shop_id']]['products_amount'] = calculate([$value[$utype],$value['quantity']],'*');
            }
//            $newshoplist[$value['shop_id']]['express_fee'] += $value['express_fee'];
            if(isset($newshoplist[$value['shop_id']]['express_fee'])){
                $newshoplist[$value['shop_id']]['express_fee'] += $value['express_fee'];
            } else {
                $newshoplist[$value['shop_id']]['express_fee'] = $value['express_fee'];
            }
            if(isset($newshoplist[$value['shop_id']]['growth_coin'])){
                $newshoplist[$value['shop_id']]['growth_coin'] += calculate([$value['growth_coin'],$value['quantity']],'*');
            } else {
                $newshoplist[$value['shop_id']]['growth_coin'] = calculate([$value['growth_coin'],$value['quantity']],'*');
            }
            $newshoplist[$value['shop_id']]['receive_id'] = $receive_id;
            $newshoplist[$value['shop_id']]['coupon_amount'] = $coupon['discount'];
            $newshoplist[$value['shop_id']]['order_amount'] = $newshoplist[$value['shop_id']]['products_amount'];
            $newshoplist[$value['shop_id']]['pay_amount'] = $newshoplist[$value['shop_id']]['products_amount'] + $newshoplist[$value['shop_id']]['express_fee'];
//            var_dump($newshoplist);die;

//            只做单个商家的下单处理（暂时）
            $newshoplist[$value['shop_id']]['pay_amount'] = calculate([$newshoplist[$value['shop_id']]['pay_amount'],$newshoplist[$value['shop_id']]['coupon_amount']],'-');
        }
//		var_dump($newshoplist);die;
//        var_dump(123);die;
        $detailModel = new \app\common\model\OrderDetail();
		$stockModel = new ProductStock();
		$paymentModel = new Payments();
        $time = time();
		$orders = [];
        $result = [
            'code' => false,
            'data' => [],
        ];
//        var_dump($user);die;
        $insertpayments = [
            "user" => $user,
            "data" => $settlemnt,
        ];
		$paymentModel->startTrans();
		$pay_id = $paymentModel->insertpayments($insertpayments,"order");
		if($pay_id === false){
            $paymentModel->rollback();
            $this->setError(-1,'插入购买记录失败');
            return $result;
        }

        if(!empty($address)){
            $insertorder['receive_name'] = $address['name'];
            $insertorder['p_c_a'] = $address['province_name'].$address['city_name'].$address['area_name'];
            $insertorder['r_address'] = $address['detail'];
            $insertorder['r_phone'] = $address['phone'];
        }
		foreach($newshoplist as $key => $value){
//		    var_dump($value);die;
		    $insertorder['data'] = $value;
		    $insertorder['data']['points'] = 0;
		    $insertorder['shop_id'] = $key;
		    $insertorder['order_type'] = $order_type;
		    $insertorder['order_time'] = $time;
		    $insertorder['user_id'] = $user['user_id'];
		    $insertorder['address_id'] = $address['address_id'];
		    $insertorder['payments_id'] = $pay_id;
		    $insertorder['receive_id'] = $receive_id??0;
            $orderid = $this->insertorder($insertorder);
            if($orderid === false){
                $paymentModel->rollback();
                $this->setError(-1,'订单生成失败');
                return $result;
            }
//            var_dump($orderid);
            $orders[] = $orderid;
//            var_dump($orders);die;
            $i = 0;
            foreach($value['product'] as $k => $v){
//                echo "<prev>";
//                var_dump($v);die;
                $insertdetail[$i]['user_id'] = $user['user_id'];
                $insertdetail[$i]['order_id'] = $orderid;
                $insertdetail[$i]['product_id'] = $v['product_id'];
                $insertdetail[$i]['product_name'] = $v['product_name'];
                $insertdetail[$i]['p_s_id'] = $v['p_s_id'];
                $insertdetail[$i]['p_s_name'] = $v['p_s_name'];
                $insertdetail[$i]['cover_url'] = $v['imageurl'];
                $insertdetail[$i]['quantity'] = $v['quantity'];
                $insertdetail[$i]['price'] = $v['price'];
                $insertdetail[$i]['sale_price'] = $v[$utype];
                $insertdetail[$i]['growth_coin'] = 0;
                $insertdetail[$i]['amount'] = calculate([$insertdetail[$i]['sale_price'],$v['quantity']],'*');

                $i += 1;

                $reduce_rs = $stockModel->reducestock($v['product_id'],$v['p_s_id'],$v['quantity']);
//                var_dump($reduce_rs);die;
                if($reduce_rs === false){
                    $paymentModel->rollback();
                    $this->setError(-1,'商品库存减少失败');
                    return $result;
                }

            }
            $res = $detailModel->saveAll($insertdetail);
            if($res === false){
                $paymentModel->rollback();
                $this->setError(-1,'订单商品信息记录失败');
                return $result;
            }
        }
        $paymentModel->commit();
		$cartModel = new Cart();
		$cartModel->delcart($user['user_id'],$ids);
		if($receive_id){
            $receiveModel = new CouponReceive();
            $params = ['is_use' => 2];
            $receiveModel->edit($params,$receive_id);
        }
//		echo "<prev>";
//		var_dump($orders);die;
//		var_dump($newshoplist);die;
//		var_dump($products);
//        var_dump($shop_ids);die;
        $result['code'] = true;
        $result['data'] = [
            'orders' => $orders,
            'paymentsid' => $pay_id,
        ];
        return $result;
    }

//    订单插入操作
    function insertorder($insertdata){
        if(!isset($insertdata['order_time'])){
            $insertdata['order_time'] = time();
        }
        $orderno = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $data = [
            'shop_id' => $insertdata['shop_id'],
            'order_type' => $insertdata['order_type'],
            'products_amount' => $insertdata['data']['products_amount'],
            'receive_id' => $insertdata['receive_id'],
            'coupon_amount' => $insertdata['data']['coupon_amount'],
            'express_fee' => $insertdata['data']['express_fee'],
            'order_amount' => $insertdata['data']['order_amount'],
            'pay_amount' => $insertdata['data']['pay_amount'],
            'order_time' => $insertdata['order_time'],
            'orderno' => $orderno,
            'user_id' => $insertdata['user_id'],
            'address_id' => $insertdata['address_id'],
            'payments_id' => $insertdata['payments_id'],
            'points' => $insertdata['data']['points'],
        ];
        if(isset($insertdata['r_address'])){
            $data['r_address'] = $insertdata['r_address'];
        }
        if(isset($insertdata['r_phone'])){
            $data['r_phone'] = $insertdata['r_phone'];
        }
        if(isset($insertdata['receive_name'])){
            $data['receive_name'] = $insertdata['receive_name'];
        }
        if(isset($insertdata['receive_time'])){
            $data['receive_time'] = $insertdata['receive_time'];
        }
        if(isset($insertdata['remark'])){
            $data['remarks'] = $insertdata['remark'];
        }
        if(isset($insertdata['order_status'])){
            $data['order_status'] = $insertdata['order_status'];
        }
        if(isset($insertdata['pay_status'])){
            $data['pay_status'] = $insertdata['pay_status'];
        }
        if(isset($insertdata['pay_time'])){
            $data['pay_time'] = $insertdata['order_time'];
        }

        if($insertdata['address_id'] != 0){
            $data['receive_name'] = $insertdata['receive_name'];
            $data['p_c_a'] = $insertdata['p_c_a'];
            $data['r_address'] = $insertdata['r_address'];
            $data['r_phone'] = $insertdata['r_phone'];
        }
        $rs = $this->save($data);
        if ($rs === false) {
            return false;
        }
        $orderid = $this->order_id;
        return $orderid;
    }

//    订单微信支付
    function wxpay($user,$paymentsid,$wxconfig,$notifyurl,$pay_end = 1,$tradetype = "JSAPI")
    {
        $paymentsModel = new Payments();
        $where = [
            'payments_id' => $paymentsid
        ];
        $payments = $paymentsModel->where($where)->find();
//        var_dump($payments);
        if($pay_end == 1){// 下单端不同参数不同 1-h5下单支付 2-小程序下单支付
            $openId = $user['wx_openid'];
            $attch['pay_end'] = '1';
        } else {
            $openId = $user['applets_openid'];
            $attch['pay_end'] = '2';
        }
        $attch = json_encode($attch,true);
        $notifyurl = request()->domain().$notifyurl;
        $input = new WxPayUnifiedOrder();
        $input->SetBody("paymentsid_".$paymentsid);
        $input->SetAttach($attch);
        $input->SetOut_trade_no($payments['order_nos']);
        $input->SetTotal_fee($payments['amount'] * 100);//订单金额以分为单位
//        $input->SetTotal_fee($order['totalfee'] * 100);//订单金额以分为单位
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 3600));
//        $input->SetGoods_tag("test");
        $input->SetNotify_url($notifyurl);
        $input->SetTrade_type($tradetype);
        $input->SetOpenid($openId);
//        var_dump($input);die;
        $config = new WxPayConfig();
        $config->appid = $wxconfig['AppID'];
        $config->secret = $wxconfig['AppSecret'];
        $config->mchid = $wxconfig['MchId'];
        $config->key = $wxconfig['MchKey'];
//        var_dump($config);
        $result = WxPayApi::unifiedOrder($config, $input);
//        var_dump($result);
        if (!empty($result["return_code"]) && strcasecmp($result["return_code"], "fail") === 0) {
//        if (!empty($result["result_code"]) && strcasecmp($result["result_code"], "FAIL") === 0) {
            $msg = empty($result["return_msg"]) ? "发生错误，下单失败" : $result["return_msg"];
//            $msg = empty($result["return_msg"]) ? "发生错误，下单失败" : $result["err_code_des"];
            $this->setError(-1,$msg);
            return false;
        }
        $tools  = new JsApiPay();
        $json_string = $tools->GetJsApiParameters($result,$config);
        $results = json_decode($json_string, true);
        $results["prepay_id"] = $result["prepay_id"];
//        dump($results);die;
        return $results;
    }

    function get_order_column($cond,$column)
    {
        $where = [];
        if(!empty($cond['orderids'])){
            $where[] = ['order_id','in',$cond['orderids']];
        }
        $rs = $this->where($where)->column($column);
        return $rs;
    }

	/**
	 * h5支付成功回调处理
	 * @param $notify
	 * @return false|void
	 * @throws \think\exception\PDOException
	 */
    function paysuccess($notify){
        $paytime = time();
		$back_info = $notify['back_info'];
		$paymentsinfo = $notify['paymentsinfo'];
		$transaction_id = $notify['transaction_id'];
		$user = $notify['user'];
        $payend = $notify['pay_end'];

        $paywhere = [
            ['user_id','=',$user['user_id']],
            ['payments_id','=',$paymentsinfo['payments_id']],
            ['status','=',1],
        ];
        $pay_data = [
            "status" => 2,
            "succeed_time" => $paytime,
            "trade_no" => $transaction_id,
            "back_message" => $back_info,
            "pay_end" => $payend,
        ];
		$payModel = new Payments();
        $payModel->startTrans();
        $pay_rs = $payModel->where($paywhere)->update($pay_data);
        if($pay_rs === false){
            $this->setError(-1,"购买记录更新失败");
            $payModel->rollback();
            return false;
        }
//
		// 增加商品销量
        $result = $payModel->execute_add_sales($paymentsinfo['payments_id']);
        if($result === false){
            $this->setError(-1,$payModel->getError());
            return false;
        }

		$data['user_profit'] = 0;
		//订单需要超过10元才计算分润
		if($paymentsinfo['amount'] >= 10){
			$growModel = new GrowthLog();
			$data = $growModel->CalculateProfit($user,$paymentsinfo,1);
			if(!$data){
				$this->setError(-1,$growModel->getError());
				return false;
			}
		}
		$orderwhere = [
			['user_id','=',$user['user_id']],
			['payments_id','=',$paymentsinfo['payments_id']],
		];
        $order_status = $paymentsinfo['payments_type'] == 'team'?4:2;
		$order_data = [
			'order_status' => $order_status,
			'pay_status' => 2,
			'pay_time' => $paytime,
			'payorderno' => $transaction_id,
			'get_growth_coin' => $data['user_profit'],
            "pay_end" => $payend,
		];
		$order_rs = $this->where($orderwhere)->update($order_data);
		if($order_rs === false){
			$this->setError(-1,"订单状态修改失败");
			$payModel->rollback();
			return false;
		}

		$payModel->commit();
        return true;
    }

	/**
	 * h5兑换商品支付成功回调处理
	 * @param $userinfo
	 * @param $paymentsid
	 * @param $payorderno
	 * @param $backinfo
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
    function exchangePaySuccess($userinfo,$paymentsid,$payorderno,$backinfo){
        $paytime = time();
        $payModel = new Payments();
        $getPayments = $payModel->order_union_product(['payments_id' => $paymentsid,'payments_type' => 'exchange'],'o.points,od.product_name,od.p_s_name,s.shop_name');
        $paywhere = [
            ['user_id','=',$userinfo['user_id']],
            ['payments_id','=',$paymentsid],
            ['status','=',1],
        ];
        $pay_data = [
            "status" => 2,
            "succeed_time" => $paytime,
            "trade_no" => $payorderno,
            "back_message" => $backinfo,
        ];
        $payModel->startTrans();
        $pay_rs = $payModel->where($paywhere)->update($pay_data);
        if($pay_rs === false){
            $this->setError(-1,"购买记录更新失败");
            $payModel->rollback();
            return false;
        }

        $orderwhere = [
            ['user_id','=',$userinfo['user_id']],
            ['payments_id','=',$paymentsid],
        ];
        $order_data = [
            'order_status' => 2,
            'pay_status' => 2,
            'pay_time' => $paytime,
            'payorderno' => $payorderno,
        ];
        $order_rs = $this->where($orderwhere)->update($order_data);
        if($order_rs === false){
            $this->setError(-1,"订单状态修改失败");
            $payModel->rollback();
            return false;
        }

        $growModel = new GrowthLog();
        $note = $getPayments[0]['shop_name'].'兑换'.$getPayments[0]['product_name'].'('.$getPayments[0]['p_s_name'].')';
        $grow_rs = $growModel->ChangeValueLog($userinfo['user_id'],6,$getPayments[0]['points'],$note,$userinfo['growth_coin']);
        if($grow_rs === false){
            $this->setError(-1,$growModel->getError());
            $payModel->rollback();
            return false;
        }
        $payModel->commit();

        $result = $payModel->execute_add_sales($paymentsid); // 增加商品销量
        if($result === false){
            $this->setError(-1,$payModel->getError());
            return false;
        }
        return true;
    }

////   线下支付成功回调处理
//    function offlinepaysuccess($notify){
//		$paytime = time();
//		$back_info = $notify['back_info'];
//		$paymentsinfo = $notify['paymentsinfo'];
//		$transaction_id = $notify['transaction_id'];
//		$user = $notify['user'];
//        $payend = $notify['pay_end'];
//
//		$paywhere = [
////			['user_id','=',$user['user_id']],
//			['payments_id','=',$paymentsinfo['payments_id']],
//			['status','=',1],
//		];
//		$pay_data = [
//			"status" => 2,
//			"succeed_time" => $paytime,
//			"trade_no" => $transaction_id,
//			"back_message" => $back_info,
//            "pay_end" => $payend,
//            "user_id" => $user['user_id'],
//		];
//		$payModel = new Payments();
//		$payModel->startTrans();
//		$pay_rs = $payModel->where($paywhere)->update($pay_data);
//		if($pay_rs === false){
//			$this->setError(-1,"购买记录更新失败");
//			$payModel->rollback();
//			return false;
//		}
////
//		// 增加商品销量
//		$result = $payModel->execute_add_sales($paymentsinfo['payments_id']);
//		if($result === false){
//			$this->setError(-1,$payModel->getError());
//			return false;
//		}
//
//		$data['user_profit'] = 0;
////		//订单需要超过10元才计算分润
////		if($paymentsinfo['amount'] >= 10){
//			$growModel = new GrowthLog();
//			$data = $growModel->CalculateProfit($user,$paymentsinfo,1);
//			if(!$data){
//				$this->setError(-1,$growModel->getError());
//				return false;
//			}
////		}
//
////        发送公众号模板推送消息
////        $this->pushTemplateMessage($user,$paymentsinfo,$data['user_profit'],$paytime);
//
//		$orderwhere = [
////			['user_id','=',$user['user_id']],
//			['payments_id','=',$paymentsinfo['payments_id']],
//		];
//		$order_data = [
//			'order_status' => 4,
//			'pay_status' => 2,
//			'pay_time' => $paytime,
//			'payorderno' => $transaction_id,
//			'get_growth_coin' => $data['user_profit'],
//            "pay_end" => $payend,
//            "user_id" => $user['user_id'],
//		];
//		$order_rs = $this->where($orderwhere)->update($order_data);
//		if($order_rs === false){
//			$this->setError(-1,"订单状态修改失败");
//			$payModel->rollback();
//			return false;
//		}
//
//		$payModel->commit();
//
//		// 改成先付款后打印
//        // 云打印机设备总单
////        $this->devices($paymentsinfo['order_id'],2);
////        // 云打印机设备总单
////        $this->devices($paymentsinfo['order_id'],1);
////        // 针式打印机设备分单
////        $this->DeviceOrderInfo($paymentsinfo['order_id'],2);
////        // 针式打印机设备总单
////        $this->DeviceOrderInfo($paymentsinfo['order_id'],1);
//
////        $data = Order::where($orderwhere)->find();
////        if($data->shop_id == 302){
////            $orderId = $data->order_id;
////            $this->devices($orderId,1);
////            $this->device($orderId,2);
////        }
//		return true;
//    }

//   线下支付成功回调处理
    function offlinepaysuccess($notify){
		$paytime = time();
		$back_info = $notify['back_info'];
		$paymentsinfo = $notify['paymentsinfo'];
		$transaction_id = $notify['transaction_id'];
		$user = $notify['user'];
        $payend = $notify['pay_end'];

		$paywhere = [
//			['user_id','=',$user['user_id']],
			['payments_id','=',$paymentsinfo['payments_id']],
			['status','=',1],
		];
		$pay_data = [
			"status" => 2,
			"succeed_time" => $paytime,
			"trade_no" => $transaction_id,
			"back_message" => $back_info,
            "pay_end" => $payend,
            "user_id" => $user['user_id'],
		];
		$payModel = new Payments();
		$payModel->startTrans();
		$pay_rs = $payModel->where($paywhere)->update($pay_data);
		if($pay_rs === false){
			$this->setError(-1,"购买记录更新失败");
			$payModel->rollback();
			return false;
		}
//
		// 增加商品销量
		$result = $payModel->execute_add_sales($paymentsinfo['payments_id']);
		if($result === false){
			$this->setError(-1,$payModel->getError());
			return false;
		}

		$data['user_profit'] = 0;
//		//订单需要超过10元才计算分润
//		if($paymentsinfo['amount'] >= 10){
//			$growModel = new GrowthLog();
//			$data = $growModel->CalculateProfit($user,$paymentsinfo,1);
//			if(!$data){
//				$this->setError(-1,$growModel->getError());
//				return false;
//			}
//		}

//        发送公众号模板推送消息
//        $this->pushTemplateMessage($user,$paymentsinfo,$data['user_profit'],$paytime);

		$orderwhere = [
//			['user_id','=',$user['user_id']],
			['payments_id','=',$paymentsinfo['payments_id']],
		];
		$order_data = [
			'order_status' => 2,
			'pay_status' => 2,
			'pay_time' => $paytime,
			'payorderno' => $transaction_id,
			'get_growth_coin' => $data['user_profit'],
            "pay_end" => $payend,
            "user_id" => $user['user_id'],
		];
		$order_rs = $this->where($orderwhere)->update($order_data);
		if($order_rs === false){
			$this->setError(-1,"订单状态修改失败");
			$payModel->rollback();
			return false;
		}

		$payModel->commit();

		// 改成先付款后打印
        // 云打印机设备总单
//        $this->devices($paymentsinfo['order_id'],2);
//        // 云打印机设备总单
//        $this->devices($paymentsinfo['order_id'],1);
//        // 针式打印机设备分单
//        $this->DeviceOrderInfo($paymentsinfo['order_id'],2);
//        // 针式打印机设备总单
//        $this->DeviceOrderInfo($paymentsinfo['order_id'],1);

//        $data = Order::where($orderwhere)->find();
//        if($data->shop_id == 302){
//            $orderId = $data->order_id;
//            $this->devices($orderId,1);
//            $this->device($orderId,2);
//        }
		return true;
    }

//    用户线下点单消费接收公众号模板消息推送
    function pushTemplateMessage($user,$paymentsinfo,$profit,$paytime)
    {
        $config = config::pull('weixin');
        $applet_config = config::pull('weixin_applet');
        $touser = $user['wx_openid'];
        $model = new Settings();
        $setting = $model->get_list(['setg'=>'push_message'])->toArray();
        $setting = array_column($setting,'value','key');
//        var_dump(array_column($setting,'value','key'));die;
        $template_id = $setting['credit_to_account'];// 公众号模板id
//            var_dump($template_id);die;
//            积分到账模板
        $data = [
            'amount3' => [
                "value" => $paymentsinfo['amount'],
            ],//消费金额
            'time6' => [
                "value" => date('Y-m-d H:i',$paytime),
            ],// 消费时间
            'number8' => [
                "value" => calculate([$user['growth_coin'],$profit],'+',2),
            ],//会员积分
            'character_string14' => [
                "value" => $paymentsinfo['orderno'],
            ],//订单号
            'thing20' => [
                "value" => $paymentsinfo['shop_name'],
            ],//商家名称
        ];
        try{
            Wechat::wxmessagepush($config,$touser,$template_id,'',$applet_config['AppID'],'',$data);
        }catch(Exception $e){
            Log::init([
                'path' => Env::get('runtime_path')."wx_push_log/",
            ]);
            Log::record($e->getMessage(),"error");
            return false;
        }
        return true;
    }

    // 打印设备
    public function DeviceOrderInfo($orderId, $type="1")
    {

        $ServAdmin = new ServiceAdmin();
        $shopModel = new Shops();
        $productModel = new Products();
        $offineModel = new OfflineRecord();
        $SeatModel = new ShopsSeat();
        $deparModel = new ShopsDepartment();

        // 获取数据
        $order = $this->getOne(['order_id' => $orderId],'order_id,shop_id,order_time,pay_amount,orderno,remarks');
        if(empty($order) || $order['shop_id'] != 302){
            return false;
        }
        $order_data = null;
        $order_data['orderno'] = $order['orderno'];
        $order_data['order_time'] = $order['order_time'];
        $order_data['remarks'] = $order['remarks'];
//        $order['shop_name'] = $shopModel->getOne(['shop_id' => $order['shop_id']],'shop_name')['shop_name'];
        $order['detail'] = $this->shops_order_details($orderId,'od.detail_id,od.order_id,od.product_name,od.product_id,od.quantity,od.sale_price,od.is_print,');
//        $seatId = $offineModel->getOne(['order_id' => $orderId],'seat_id')['seat_id'];
//        $order_data['table'] = $SeatModel->getOne(['seat_id' => $seatId],'seat_num')['seat_num'];
        if($type == 1){
            // 总单
            $order_data['detail'] = $order['detail'];
            if($order['shop_id'] == 302){
                $key = $deparModel->getOne(['department_id' => 12],'printer_parameter')['printer_parameter'];
                $rs = $this->device($key, $orderId,0);
            }


        }else{
            // 分单
            foreach ($order['detail'] as $key => $val){

                $deparId = $productModel->getOne(['product_id' => $val['product_id']],'department_id')['department_id'];
                if(!$deparId){
                    return false;
                }
                $key = $deparModel->getOne(['department_id' => $deparId],'printer_parameter')['printer_parameter'];



                if($val['is_print'] == 1){
//                $rs = $this->device($order['orderno'],$order['table'],$val['product_name'],$val['quantity'],$order['order_time'],$order['remarks']);
                    $rs = $this->device($key, $orderId, $val['detail_id']);

                    if($rs === true){
                        $rs1 = \app\common\model\OrderDetail::where(['detail_id' => $val['detail_id']])->update(['is_print' => 2]);
                    }
                }
            }

        }


    }


    public function device($key, $orderId, $detail_id=0)
    {
//        return redirect('http://bfyc.jiazhengdashi.com/applets/prints?order_data='.$order_data);
//        $order_data = json_encode($order_data,true);

//        var_dump("http://bfyc.jiazhengdashi.com/applets/prints?order_data=".$order_data);die;
        $param = array(
            "key" => $key,
            "sourceFile" => "http://bfyc.jiazhengdashi.com/applets/prints?order_id=".$orderId."&detail_id=".$detail_id,
            "Type" => "html",//支持的类型：img,pdf,html,doc,docx,xls,xlsx,ppt,pptx
            "filename" => "",
            "trueColor" => "True",//是否彩色打印,取值：True或False
            "Copies" => "1",//打印份数,取值：1~100
            "Landscape" => "False",//打印内容是否旋转90度,取值：True或False
            "Scaling" => "True",//打印内容是否自适应纸张大小,取值：True或False
            "tasktype" => "now",//打印任务类型，可选定是立即打印还是定时打印,取值：now或plan
            "printtime" => time(),//打印任务类型为plan时，打印任务执行的时间点。时间戳类型
            "paperWidth" => "",//定义打印内容的宽度单位mm
            "paperHeight" => "",//定义打印内容的高度单位mm
            "leftMargin" => "0.01",//定义打印内容的左边留白单位mm
            "topMargin" => "0.01",//定义打印内容的顶边留白单位mm
            "callBackUrl" => "指定一个接收打印状态的回调地址。"
        );
        $apiURL = "http://www.eyprint.com/public/";
        $responseJson = SHttp::http_curl($apiURL, $param, '', 'post');
        $json = json_decode($responseJson['str'], true);
        if($json['result'] == "success"){
            return true;
        }
    }


     //打印设备
    public function devices($orderId, $type)
    {

        $ServAdmin = new ServiceAdmin();
        $shopModel = new Shops();
        $offineModel = new OfflineRecord();
        $SeatModel = new ShopsSeat();

        // 获取数据
        $order = $this->getOne(['order_id' => $orderId],'order_id,shop_id,order_time,pay_amount,orderno,remarks');
        if(empty($order) || $order['shop_id'] != 302){
            return false;
        }
        $order['shop_name'] = $shopModel->getOne(['shop_id' => $order['shop_id']],'shop_name')['shop_name'];
        $order['detail'] = $this->shops_order_details($orderId,'od.detail_id,od.order_id,od.product_name,od.quantity,od.sale_price,');
        $seatId = $offineModel->getOne(['order_id' => $orderId],'seat_id')['seat_id'];
        $order['table'] = $SeatModel->getOne(['seat_id' => $seatId],'seat_num')['seat_num'];
//        if($type == 1){
            $rs = $ServAdmin->GetDevice($order, $type);
//        }
//        elseif($type == 2){
//            foreach ($order['detail'] as $key => $val){
//                $order['product_name'] = $val['product_name'];
//                $order['quantity'] = $val['quantity'];
//
//                $rs = $ServAdmin->GetDevice($order, $type);
//            }
//        }
    }

//    非购物车的下单验证（验证商品计算价格）
    function checkplace($user,$product_id,$stock_id,$quantity,$receive_id){
        $productModel = new Products();
        $item = "p.*,ps.p_s_id,ps.p_s_name,ps.stock,s.shop_id,s.shop_name,s.imagesurl";
        $product = $productModel->check_uncommon_product($product_id,$stock_id,$item);
        if($product === false){
            $this->setError(-1,$productModel->getError());
            return false;
        }
        if($product['stock'] < $quantity){
            $this->setError(-1,"该商品库存不足");
            return false;
        }
        if($product['class_id'] == 2){
            if($product['integral'] > $user['growth_coin']){
                $this->setError(-1,"用户积分不足以兑换该商品");
                return false;
            }
        }
        if($product['class_id'] == 3){
            $begintime = strtotime(date('Y-m-d').'00:00:00');;
            $endtime = strtotime(date('Y-m-d').'23:59:59');
            $orderModel = new Order();
            $findtoday = $orderModel
                ->where('user_id','=',$user['user_id'])
                ->where('order_type','=',3)
                ->where('order_time','between',[$begintime,$endtime])
                ->find();
            if($findtoday){
                $this->setError(-1,"用户今日已领取免费爱心餐");
                return false;
            }
        }
        // 会员折扣
        $utype = $user['utype'] == 2 ?'mprice':'sprice';
        $product['sale_price'] = $product[$utype];
        $data = [
            'productinfo' => $product,
            'coupon' => [],
        ];
        $utype = $user['utype'] == 2 ?'mprice':'sprice';
        //商品总价
        $allproduct_amount = calculate([$product[$utype],$quantity],'*');
        //商品总积分
        $allpoints = calculate([$product['integral'],$quantity],'*',0);
        //订单使用优惠券减少的金额
        $allcoupon_amount = 0.00;
        //总运费
        $allexpress_fee = $product['express_fee'];
        //订单总价 = 商品总价-优惠券金额(不包含运费)
        $allorder_amount = 0.00;
        // 计算商品下单可获得积分
        $all_growth_coin = calculate([$product['growth_coin'],$quantity],'*',0);;
        //优惠卷使用情况
        $is_coupon = true;

        if($receive_id){
            $CouponReceiveModel = new CouponReceive();
            $coupon = $CouponReceiveModel->where(['receive_id'=>$receive_id,'user_id'=>$user['user_id'],'is_use'=>1])->find();
            if(empty($coupon)){
                $this->setError(-1,"无效消费券");
                return false;
            }
            $coupon = $coupon->toArray();
            $data['coupon'] = $coupon;
            if($coupon && $allproduct_amount >= $coupon['fullmoney']){
                //计算订单使用优惠券减少的金额
                $allcoupon_amount = $coupon['discount'];
                //计算订单总价
                $allorder_amount = calculate([$allproduct_amount,$coupon['discount']],'-');
            } else {
                //计算订单使用优惠券减少的金额
                $allcoupon_amount = 0;
                //计算订单总价
                $allorder_amount = $allproduct_amount;
                $is_coupon = false;
//                $this->setError(-1,"未达使用要求");
//                return false;
            }
        } else {
            $allorder_amount = $allproduct_amount;
        }
        $pay_amount = calculate([$allorder_amount,$allexpress_fee],'+');
        $data['is_coupon'] = $is_coupon;
        $data['payinfo'] = [
            'allproduct_amount' => $allproduct_amount,
            'allpoints' => $allpoints,
            'allcoupon_amount' => $allcoupon_amount,
            'allexpress_fee' => $allexpress_fee,
            'allorder_amount' => $allorder_amount,
            'pay_amount' => $pay_amount,
            'all_growth_coin' => $all_growth_coin,
        ];
        return $data;
    }

//    处理兑换商品订单插入数据
    function placeexchangeorder($user,$data,$quantity,$address){
        $detailModel = new \app\common\model\OrderDetail();
        $stockModel = new ProductStock();
        $time = time();
        $result = [
            'code' => false,
            'data' => [],
        ];
//        var_dump($user);die;
        $paydata = [
            'products_amount' => $data['payinfo']['allproduct_amount'],
            'coupon_amount' => $data['payinfo']['allcoupon_amount'],
            'express_fee' => $data['payinfo']['allexpress_fee'],
            'order_amount' => $data['payinfo']['allorder_amount'],
            'pay_amount' => $data['payinfo']['pay_amount'],
            'points' => $data['payinfo']['allpoints'],
        ];
        $insertorder['data'] = $paydata;
        $insertorder['shop_id'] = $data['productinfo']['shop_id'];
        $insertorder['order_type'] = 2;
        $insertorder['order_time'] = $time;
        $insertorder['user_id'] = $user['user_id'];
        $insertorder['address_id'] = $address['address_id'];
        $insertorder['receive_id'] = 0;

        $payments_id = 0;
        $this->startTrans();
        if($data['payinfo']['pay_amount'] > 0){ // 是否需要走支付流程，靠$payments_id
            $paymentModel = new Payments();
            $insertpayments = [
                "user" => $user,
                "data" => $data['payinfo'],
            ];
            $payments_id = $paymentModel->insertpayments($insertpayments,"exchange");
            if($payments_id === false){
                $paymentModel->rollback();
                $this->setError(-1,'插入购买记录失败');
                return $result;
            }
            $insertorder['payments_id'] = $payments_id;
        } else {
            $insertorder['order_status'] = 2;
            $insertorder['pay_status'] = 2;
            $insertorder['payments_id'] = $payments_id;
        }
        if(!empty($address)){
            $insertorder['receive_name'] = $address['name'];
            $insertorder['p_c_a'] = $address['province_name'].$address['city_name'].$address['area_name'];
            $insertorder['r_address'] = $address['detail'];
            $insertorder['r_phone'] = $address['phone'];
        }
        $orderid = $this->insertorder($insertorder);
        if($orderid === false){
            $this->rollback();
            $this->setError(-1,'订单生成失败');
            return $result;
        }

        $utype = $user['utype'] == 2 ?'mprice':'sprice';
        $insertdetail['user_id'] = $user['user_id'];
        $insertdetail['order_id'] = $orderid;
        $insertdetail['product_id'] = $data['productinfo']['product_id'];
        $insertdetail['product_name'] = $data['productinfo']['product_name'];
        $insertdetail['p_s_id'] = $data['productinfo']['p_s_id'];
        $insertdetail['p_s_name'] = $data['productinfo']['p_s_name'];
        $insertdetail['cover_url'] = $data['productinfo']['imageurl'];
        $insertdetail['quantity'] = $quantity;
        $insertdetail['price'] = $data['productinfo']['price'];
        $insertdetail['sale_price'] = $data['productinfo'][$utype];
        $insertdetail['growth_coin'] = $data['productinfo']['integral'];
        $insertdetail['amount'] = calculate([$insertdetail['sale_price'],$quantity],'*',0);
        $insertdetail['growth_coin_amount'] = calculate([$insertdetail['growth_coin'],$quantity],'*',0);
        $res = $detailModel->insertorderdetail($insertdetail);
        if($res === false){
            $this->rollback();
            $this->setError(-1,'订单商品信息记录失败');
            return $result;
        }
//
        $reduce_rs = $stockModel->reducestock($data['productinfo']['product_id'],$data['productinfo']['p_s_id'],$quantity);
//        var_dump($reduce_rs);die;
        if($reduce_rs === false){
            $this->rollback();
            $this->setError(-1,'商品库存减少失败');
            return $result;
        }
        $userModel = new User();
        $user_rs = $userModel->reducepoints($user,$paydata['points']);
        if($user_rs === false){
            $this->rollback();
            $this->setError(-1,'用户积分减少失败');
            return $result;
        }
        $this->commit();
        $this->pushExchangeMessage($user,$time,"{$data['productinfo']['product_name']}",$paydata['points']);
        $result['code'] = true;
        $result['data'] = [
            'orderid' => $orderid,
            'paymentsid' => $payments_id,
        ];
        return $result;
    }

//    用户兑换商品接受小程序订阅推送信息
    function pushExchangeMessage($user,$paytime,$note,$points)
    {
        $applet_config = config::pull('weixin_applet');
        $applet_touser = $user['applets_openid'];
        $model = new Settings();
        $setting = $model->get_list(['setg'=>'push_message'])->toArray();
        $setting = array_column($setting,'value','key');
//        var_dump(array_column($setting,'value','key'));die;
        $template_id = $setting['integral_change'];// 小程序模板id
//            积分变动模板
        $data = [
            'time7' => [
                "value" => date('Y-m-d H:i:s',$paytime),
            ],// 变动时间
            'thing8' => [
                "value" => '兑换商品',
            ],//变动原因
            'thing10' => [
                "value" => $note,
            ],//兑换内容
            'number12' => [
                "value" => $points,
            ],//扣减积分
            'number14' => [
                "value" => calculate([$user['growth_coin'],$points],'-',2),
            ],//可用积分
        ];
        try{
            Wechat::messagepush($applet_config,$applet_touser,$template_id,'',$data);
        }catch(Exception $e){
            Log::init([
                'path' => Env::get('runtime_path')."app_push_log/",
            ]);
            Log::record($e->getMessage(),"error");
            return false;
        }
        return true;
    }

//    处理团餐订单插入数据
    function placeteamorder($user,$data,$quantity,$reserve_info,$receive_id){
        $detailModel = new \app\common\model\OrderDetail();
        $stockModel = new ProductStock();
        $time = time();
        $result = [
            'code' => false,
            'data' => [],
        ];
//        var_dump($user);die;
        $paydata = [
            'products_amount' => $data['payinfo']['allproduct_amount'],
            'coupon_amount' => $data['payinfo']['allcoupon_amount'],
            'express_fee' => $data['payinfo']['allexpress_fee'],
            'order_amount' => $data['payinfo']['allorder_amount'],
            'pay_amount' => $data['payinfo']['pay_amount'],
            'points' => $data['payinfo']['allpoints'],
            'growth_coin' => $data['payinfo']['all_growth_coin'],
        ];
        $insertorder['data'] = $paydata;
        $insertorder['shop_id'] = $data['productinfo']['shop_id'];
        $insertorder['order_type'] = 4;
        $insertorder['order_time'] = $time;
        $insertorder['user_id'] = $user['user_id'];
        $insertorder['address_id'] = 0;
        $insertorder['receive_id'] = $receive_id??0;

        $this->startTrans();
        $paymentModel = new Payments();
        $insertpayments = [
            "user" => $user,
            "data" => $data['payinfo'],
        ];
        $payments_id = $paymentModel->insertpayments($insertpayments,"team");
        if($payments_id === false){
            $paymentModel->rollback();
            $this->setError(-1,'插入购买记录失败');
            return $result;
        }
        $insertorder['payments_id'] = $payments_id;
        $orderid = $this->insertorder($insertorder);
        if($orderid === false){
            $this->rollback();
            $this->setError(-1,'订单生成失败');
            return $result;
        }
        $reserve_info['order_id'] = $orderid;
        $reserve_info['user_id'] = $user['user_id'];
        $reserveOrder = new Reserveorder();
        $reserve_res = $reserveOrder->insertrecord($reserve_info);
        if($reserve_res === false){
            $this->rollback();
            $this->setError(-1,'插入预约信息失败，'.$reserveOrder->getError());
            return $result;
        }
        $grModel = new GoodsRecord();
        $gr_rs = $grModel->InsertGoodsRecord($user,$data['productinfo'],$orderid,'team');
        if($gr_rs === false){
            $this->rollback();
            $this->setError(-1,'插入团餐记录失败，'.$grModel->getError());
            return $result;
        }

        $utype = $user['utype'] == 2 ?'mprice':'sprice';
        $insertdetail['user_id'] = $user['user_id'];
        $insertdetail['order_id'] = $orderid;
        $insertdetail['product_id'] = $data['productinfo']['product_id'];
        $insertdetail['product_name'] = $data['productinfo']['product_name'];
        $insertdetail['p_s_id'] = $data['productinfo']['p_s_id'];
        $insertdetail['p_s_name'] = $data['productinfo']['p_s_name'];
        $insertdetail['cover_url'] = $data['productinfo']['imageurl'];
        $insertdetail['quantity'] = $quantity;
        $insertdetail['price'] = $data['productinfo']['price'];
        $insertdetail['sale_price'] = $data['productinfo'][$utype];
        $insertdetail['growth_coin'] = $data['productinfo']['integral'];
        $insertdetail['amount'] = calculate([$insertdetail['sale_price'],$quantity],'*',0);
        $res = $detailModel->insertorderdetail($insertdetail);
        if($res === false){
            $this->rollback();
            $this->setError(-1,'订单商品信息记录失败');
            return $result;
        }
//
        $reduce_rs = $stockModel->reducestock($data['productinfo']['product_id'],$data['productinfo']['p_s_id'],$quantity);
//        var_dump($reduce_rs);die;
        if($reduce_rs === false){
            $this->rollback();
            $this->setError(-1,'商品库存减少失败');
            return $result;
        }
        $this->commit();
        if($receive_id){
            $receiveModel = new CouponReceive();
            $params = ['is_use' => 2];
            $receiveModel->edit($params,$receive_id);
        }
        $result['code'] = true;
        $result['data'] = [
            'orderid' => $orderid,
            'paymentsid' => $payments_id,
        ];
        return $result;
    }

//    处理爱心餐订单插入数据
    function placeloveorder($user,$data,$quantity){
        $detailModel = new \app\common\model\OrderDetail();
        $stockModel = new ProductStock();
        $time = time();
        $result = [
            'code' => false,
            'data' => [],
        ];
//        var_dump($user);die;
        $paydata = [
            'products_amount' => $data['payinfo']['allproduct_amount'],
            'coupon_amount' => $data['payinfo']['allcoupon_amount'],
            'express_fee' => $data['payinfo']['allexpress_fee'],
            'order_amount' => $data['payinfo']['allorder_amount'],
            'pay_amount' => $data['payinfo']['pay_amount'],
            'points' => $data['payinfo']['allpoints'],
        ];
        $insertorder['data'] = $paydata;
        $insertorder['shop_id'] = $data['productinfo']['shop_id'];
        $insertorder['order_type'] = 3;
        $insertorder['order_time'] = $time;
        $insertorder['user_id'] = $user['user_id'];
        $insertorder['address_id'] = 0;
        $insertorder['receive_id'] = 0;
        $insertorder['order_status'] = 4;
        $insertorder['pay_status'] = 2;
        $insertorder['payments_id'] = 0;
        $insertorder['pay_time'] = true;

        $this->startTrans();
        $orderid = $this->insertorder($insertorder);
        if($orderid === false){
            $this->rollback();
            $this->setError(-1,'订单生成失败');
            return $result;
        }

        $grModel = new GoodsRecord();
        $gr_rs = $grModel->InsertGoodsRecord($user,$data['productinfo'],$orderid,'love');
        if($gr_rs === false){
            $this->rollback();
            $this->setError(-1,$grModel->getError());
            return $result;
        }

        $utype = $user['utype'] == 2 ?'mprice':'sprice';
        $insertdetail['user_id'] = $user['user_id'];
        $insertdetail['order_id'] = $orderid;
        $insertdetail['product_id'] = $data['productinfo']['product_id'];
        $insertdetail['product_name'] = $data['productinfo']['product_name'];
        $insertdetail['p_s_id'] = $data['productinfo']['p_s_id'];
        $insertdetail['p_s_name'] = $data['productinfo']['p_s_name'];
        $insertdetail['cover_url'] = $data['productinfo']['imageurl'];
        $insertdetail['quantity'] = $quantity;
        $insertdetail['price'] = $data['productinfo']['price'];
        $insertdetail['sale_price'] = $data['productinfo'][$utype];
        $insertdetail['growth_coin'] = $data['productinfo']['integral'];
        $insertdetail['amount'] = calculate([$insertdetail['sale_price'],$quantity],'*',0);
        $insertdetail['growth_coin_amount'] = calculate([$insertdetail['growth_coin'],$quantity],'*',0);
        $res = $detailModel->insertorderdetail($insertdetail);
        if($res === false){
            $this->rollback();
            $this->setError(-1,'订单商品信息记录失败');
            return $result;
        }
//
        $reduce_rs = $stockModel->reducestock($data['productinfo']['product_id'],$data['productinfo']['p_s_id'],$quantity);
//        var_dump($reduce_rs);die;
        if($reduce_rs === false){
            $this->rollback();
            $this->setError(-1,'商品库存减少失败');
            return $result;
        }
        $this->commit();
        $result['code'] = true;
        $result['data'] = [
            'orderid' => $orderid,
        ];
        return $result;
    }

//    操作确认提醒发货
    function operateremind($condition){
        $where[] = ['order_id','=',$condition['order_id']];

        if(!empty($condition['user_id'])){
            $where[] = ['user_id', '=', $condition['user_id']];
        }
        $order = $this->getOne($where);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
        $order = $order->toArray();
        if($order['is_remind'] == 2){
            $this->setError(-1,'该订单已提醒');
            return false;
        }
        if($order['order_type'] != 1 && $order['order_type'] != 2){
            $this->setError(-1,'订单类型有误');
            return false;
        }
        if($order['order_status'] != 2 || $order['pay_status'] != 2){
            $this->setError(-1,'订单状态有误');
            return false;
        }
        $param = [
            'is_remind' => 2,
        ];
        $rs = $this->where("order_id",'=',$order['order_id'])->update($param);
        if($rs === false){
            $this->setError(-1,'操作失败');
            return false;
        }
        return true;
    }

////    操作取消订单
//    function operatecancel($condition){
//        $where[] = ['order_id','=',$condition['order_id']];
//
//        if(!empty($condition['user_id'])){
//            $where[] = ['user_id', '=', $condition['user_id']];
//        }
//        $order = $this->getOne($where);
//        if(empty($order)){
//            $this->setError(-1,'用户不存在该订单');
//            return false;
//        }
//        $order = $order->toArray();
////        var_dump($order);die;
//        if($order['order_status'] != 1 || $order['pay_status'] != 1){
//            $this->setError(-1,'订单状态有误不允许取消');
//            return false;
//        }
//        $item = 'od.*';
//        $join = [
//            ['ddt_order o','od.order_id = o.order_id'],
//        ];
//        $details = $this->api_order_details2($order['order_id'],$item,$join);
////        var_dump($details);die;
//        if(empty($details)){
//            $this->setError(-1,'订单商品数据有误');
//            return false;
//        }
//        $rs = $this->updateorderandstock($details,$order);
//        return $rs;
//    }

//    操作撤销订单
    function operatecancel($condition){
        $where[] = ['order_id','=',$condition['order_id']];

        if(!empty($condition['user_id'])){
            $where[] = ['user_id', '=', $condition['user_id']];
        }
        $order = $this->getOne($where);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
        $order = $order->toArray();
//        var_dump($order);die;
        if($order['order_status'] != 3 || $order['order_status'] != 2){
            $this->setError(-1,'订单状态有误不允许撤销');
            return false;
        }
        $param = [
            'order_status' => 6,
        ];
        $rs = $this->where("order_id",'=',$order['order_id'])->update($param);
        if($rs === false){
            return false;
        }
        return $rs;
    }

//    操作取消撤销订单操作
    function operatecanceloperation($condition){
        $where[] = ['order_id','=',$condition['order_id']];

        if(!empty($condition['user_id'])){
            $where[] = ['user_id', '=', $condition['user_id']];
        }
        $order = $this->getOne($where);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
        $order = $order->toArray();
//        var_dump($order);die;
        if($order['order_status'] != 6){
            $this->setError(-1,'操作错误');
            return false;
        }
        $param = [
            'order_status' => 3,
        ];
        $rs = $this->where("order_id",'=',$order['order_id'])->update($param);
        if($rs === false){
            return false;
        }
        return $rs;
    }

//    用户修改订单
    function usereditorder($condition,$param){
        $where[] = ['order_id','=',$condition['order_id']];

        if(!empty($condition['user_id'])){
            $where[] = ['user_id', '=', $condition['user_id']];
        }
        $order = $this->getOne($where);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
        $order = $order->toArray();
//        var_dump($order);die;
        if($order['order_status'] != 3 || $order['order_status'] != 2){
            $this->setError(-1,'不允许修改');
            return false;
        }
        $rs = $this->where("order_id",'=',$order['order_id'])->update($param);
        if($rs === false){
            return false;
        }
        return $rs;
    }

//    操作确认订单
    function operatesure($condition){
        $where[] = ['order_id','=',$condition['order_id']];

        if(!empty($condition['user_id'])){
            $where[] = ['user_id', '=', $condition['user_id']];
        }
        $order = $this->getOne($where);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
        $order = $order->toArray();
        if($order['order_status'] != 3 || $order['pay_status'] != 2){
            $this->setError(-1,'订单状态有误不允许操作');
            return false;
        }
        $param = [
            'order_status' => 4,
        ];
        $rs = $this->where("order_id",'=',$order['order_id'])->update($param);
        if($rs === false){
            $this->setError(-1,'操作失败');
            return false;
        }
        return true;
    }

//    操作删除订单
    function operatedelete($condition){
        $where[] = ['order_id','=',$condition['order_id']];

        if(!empty($condition['user_id'])){
            $where[] = ['user_id', '=', $condition['user_id']];
        }
        $order = $this->getOne($where);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
        $order = $order->toArray();
        if($order['order_type'] != 4){
            $this->setError(-1,'该类型订单不允许删除');
            return false;
        }
        if($order['order_status'] != 4 || $order['pay_status'] != 2){
            $this->setError(-1,'订单状态有误不允许操作');
            return false;
        }
        $param = [
            'is_del' => 2,
        ];
        $rs = $this->where("order_id",'=',$order['order_id'])->update($param);
        if($rs === false){
            $this->setError(-1,'操作失败');
            return false;
        }
        return true;
    }

//    更新订单为取消状态并回退库存
    function updateorderandstock($details,$order){
        $stockModel = new ProductStock();
        $this->startTrans();
        $stock_rs = $stockModel->batchstock($details,'+');
//        var_dump($stock_rs);
        if($stock_rs === false){
            $this->rollback();
            $this->setError(-1,$stockModel->getError());
            return false;
        }
        $param = [
            'order_status' => 5,
            'pay_status' => 3,
        ];
        $rs = $this->where("order_id",'=',$order['order_id'])->update($param);
        if($rs === false){
            $this->rollback();
            $this->setError(-1,'操作失败');
            return false;
        }
        $this->commit();
        return true;
    }

//    验证待支付订单商品和店铺(商品或者店铺下架则自动取消订单）
    function tobepaidordercheck($condition){
        $result = [
            "code" => -1,
            "msg" => '',
            "data" => [],
        ];
        $where[] = ['order_id','=',$condition['order_id']];

        if(!empty($condition['user_id'])){
            $where[] = ['user_id', '=', $condition['user_id']];
        }
        $order = $this->getOne($where);
        if(empty($order)){
            $result['msg'] = '用户不存在该订单';
            return $result;
        }
        $order = $order->toArray();
//        var_dump($order);die;
        if($order['order_status'] != 1 || $order['pay_status'] != 1){
            $result['msg'] = '订单状态有误不允许取消';
            return $result;
        }
        $item = 'od.*,s.shop_id,s.approved as s_approved,s.state as s_state,s.shop_type,p.is_del as p_del,p.state as p_state,p.approved as p_approved,ps.is_del as ps_del';
        $join = [
            ['ddt_order o','od.order_id = o.order_id'],
            ['ddt_shops s','o.shop_id = s.shop_id'],
            ['ddt_products p','od.product_id = p.product_id'],
            ['ddt_products_stock ps','od.p_s_id = ps.p_s_id'],
        ];
        $details = $this->api_order_details($order['order_id'],$item,$join);
        if(empty($details)){
            $result['msg'] = '订单商品数据有误';
            return $result;
        }
        $result['code'] = 1;
        $result['msg'] = '验证通过';
        $result['data'] = [
            'order' => $order,
            'details' => $details,
        ];
        if($details[0]['s_state'] != 1 || $details[0]['s_approved'] != 1){
            $result['code'] = 2;
            $result['msg'] = '该商铺已下架';
        }
//        var_dump($details);
        foreach($details as $value){
//            库存id不为0且未删除，商品通过审核且上架未被删除
            if(($value['ps_del'] != 1 && $value['p_s_id'] != 0) || $value['p_del'] != 1 || $value['p_state'] != 1 || $value['p_approved'] != 2){
                $result['code'] = 2;
                $result['msg'] = '订单中部分商品已下架';
                return $result;
            }
        }
        return $result;
    }

//    用户评价操作
    function operatecomment($condition,$params,$pic_number = 3){
        $where[] = ['o.order_id','=',$condition['order_id']];
        $where[] = ['o.user_id', '=', $condition['user_id']];
        $where[] = ['od.detail_id', '=', $condition['detail_id']];
        if(empty($params['content'])){
            $this->setError(-1,'必填项不能为空');
            return false;
        }
        $params['images'] = trim($params['images'],'"');
        if(!is_array($params['images'])){
            $params['images'] = explode(',',$params['images']);
        }
        if(count($params['images']) > $pic_number){
            $this->setError(-1,"上传图片不能超过{$pic_number}张");
            return false;
        }
        $item = 'o.*,od.detail_id,ps.*';
        $join = [
            ['ddt_orderdetail od','o.order_id = od.order_id'],
            ['ddt_products_stock ps','od.p_s_id = ps.p_s_id'],
        ];
        $order = $this->getJoinOrder($where,$item,$join);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
//        var_dump($params);
//        var_dump($order);die;
        if($order['order_status'] != 4 || $order['pay_status'] != 2){
            $this->setError(-1,'该订单还未完成不能评价');
            return false;
        }
        $stock_info = [
            "p_s_id" => $order['p_s_id'],
            "p_s_name" => $order['p_s_name'],
            "g_m_details" => $order['g_m_details'],
            "g_m_paper" => $order['g_m_paper'],
            "stock" => $order['stock'],
            "product_id" => $order['product_id'],
            "add_time" => $order['add_time'],
            "update_time" => $order['update_time'],
            "is_del" => $order['is_del'],
        ];
//        var_dump($stock_info);die;
        $data = [
            'content' => $params['content'],
            'star' => 5,
            'user_id' => $order['user_id'],
            'product_id' => $order['product_id'],
            'order_detail_id' => $order['detail_id'],
            'proterty_details' => json_encode($stock_info,true),
            'order_id' => $order['order_id'],
            'images' => implode(',',array_filter($params['images'])),
        ];
//        var_dump($data);die;
        $commitModel = new Commit();
        $this->startTrans();
        $rs = $commitModel->edit($data);
        if($rs === false){
            $this->rollback();
            $this->setError(-1,'插入记录失败');
            return false;
        }
        $rs = $this->update(['is_comment' => 1],['order_id' => $order['order_id']]);
        if($rs === false){
            $this->rollback();
            $this->setError(-1,'更新订单评价状态失败');
            return false;
        }
        $detailModel = new OrderDetail();
        $rs = $detailModel->edit(['is_comment' => 1],$order['detail_id']);
        if($rs === false){
            $this->rollback();
            $this->setError(-1,'更新评价状态失败');
            return false;
        }
        $this->commit();
        return true;
    }

//    用户评价操作
    function operateaftersales($condition,$params,$pic_number = 3){
        $where[] = ['o.order_id','=',$condition['order_id']];
        $where[] = ['o.user_id', '=', $condition['user_id']];
        $where[] = ['od.detail_id', '=', $condition['detail_id']];
        if(empty($params['content']) || empty($params['a_s_type'])){
            $this->setError(-1,'必填项不能为空');
            return false;
        }
        if(!is_array($params['images'])){
            $params['images'] = explode(',',$params['images']);
        }
//        var_dump(is_array($params['images']));
//        var_dump($params['images']);die;
        $params['images'] = array_filter($params['images']);
        if(empty($params['images'])){
            $this->setError(-1,"请上传图片凭证");
            return false;
        }
        if(count($params['images']) > $pic_number){
            $this->setError(-1,"上传图片不能超过{$pic_number}张");
            return false;
        }
        $afterModel = new Aftersales();
        $after = $afterModel->getOne([['user_id','=',$condition['user_id']],['order_detail_id','=',$condition['detail_id']],['is_show','=',1]]);
//        var_dump($after);die;
        if($after){
           $this->setError(-1,'该商品已申请售后，请等待客服联系');
           return false;
        }
        $item = 'od.*,o.shop_id,o.order_status,o.pay_status,o.orderno,o.order_time,o.pay_time,o.order_type,ps.*';
        $join = [
            ['ddt_orderdetail od','o.order_id = od.order_id'],
            ['ddt_products_stock ps','od.p_s_id = ps.p_s_id'],
        ];
        $order = $this->getJoinOrder($where,$item,$join);
        if(empty($order)){
            $this->setError(-1,'用户不存在该订单');
            return false;
        }
//        var_dump($params);
        if($order['order_status'] != 4 || $order['pay_status'] != 2){
            $this->setError(-1,'该订单还未完成不能申请售后');
            return false;
        }
        $data = [
            'content' => $params['content'],
            'images' => implode(',',$params['images']),
            'user_id' => $order['user_id'],
            'order_id' => $order['order_id'],
            'order_detail_id' => $order['detail_id'],
            'product_id' => $order['product_id'],
            'stock_id' => $order['p_s_id'],
            'order_product_details' => json_encode($order->toArray(),true),
            'shop_id' => $order['shop_id'],
            'a_s_type' => $params['a_s_type'],
        ];
//        var_dump($data);die;
        $rs = $afterModel->edit($data);
        if($rs === false){
            $this->setError(-1,$afterModel->getError());
            return false;
        }
        return $rs;
    }


    function get_aftersale_list($cond,$orderby,$limit,$is_page = true,$ofield = ['o.*','s.shop_name','u.user_id','u.nick_name'],$dfield = ['*'])
    {
        $where = [];

        if(!empty($cond['shop_name'])){
            $where[] = ['s.shop_name','like','%'.$cond['shop_name'].'%'];
        }
        if(!empty($cond['shop_id'])){
            $where[] = ['o.shop_id','=',$cond['shop_id']];
        }
        if(!empty($cond['user_id'])){
            $where[] = ['o.user_id','=',$cond['user_id']];
        }
        if(!empty($cond['pay_status'])){
            $where[] = ['o.pay_status','=',$cond['pay_status']];
        }
        if(!empty($cond['order_status'])){
            $where[] = ['o.order_status','=',$cond['order_status']];
        }
        if(!empty($cond['order_type'])){
            $where[] = ['o.order_type','=',$cond['order_type']];
        }
        if(!empty($cond['class_ids'])){
            $where[] = ['o.order_type','in',$cond['class_ids']];
        }
        if(isset($cond['is_comment'])){
            $where[] = ['o.is_comment','in',$cond['is_comment']];
        }
        if(!empty($cond['time'])){
            $array = explode(' - ',input('get.time'));
            $start = strtotime($array[0]." 00:00:00");
            if($array[0] == $array[1]){
                $end = strtotime($array[0]." 23:59:59");
            } else {
                $end = strtotime($array[1]." 00:00:00");
            }
            $where[] = ['o.order_time','between',[$start,$end]];
        }

        $jion = [
            ['ddt_shops s','o.shop_id = s.shop_id'],
            ['ddt_user u','o.user_id = u.user_id'],
        ];
        $OrderDetailModel = new OrderDetail();
        if(!empty($cond['product_name'])){
            $orderids = $OrderDetailModel
                ->where('user_id','=',$cond['user_id'])
                ->where('product_name','like','%'.$cond['product_name'].'%')
                ->distinct(true)
                ->column('order_id');
            $where[] = ['o.order_id','in',implode(',',$orderids)];
        }


        $data = $this
            ->alias('o')
            ->field($ofield)
            ->where($where)
            ->leftjoin($jion)
            ->order($orderby)
            ->paginate($limit);
//        echo $this->getLastSql();die;
        if($is_page){
            $page = $data->render();
        }else{
            $page = [
                "total"=> $data->total(),
                "per_page"=> $data->listRows(),
                "current_page"=> $data->currentPage(),
                "last_page"=> $data->lastPage(),
            ];
        }

        //处理一个主订单表对应多订单详情表逻辑
        if($data->toArray()){
            $data = $data->toArray()['data'];
            $lists = array_column($data,null,'order_id');
            $order_ids = implode(',',array_column($data,'order_id'));
            $DetailList = $OrderDetailModel->field($dfield)->where([
                ['order_id','in',$order_ids]
            ])->select()->toArray();
            foreach($DetailList as $key => $value){
                $lists[$value['order_id']]['number'] = $lists[$value['order_id']]['number']??0 + $value['quantity'];
                $lists[$value['order_id']]['children'][] = $value;
            }
            $data = array_values($lists);
        }
        return ['data'=>$data,'page'=>$page];
    }

    function checkOfflineOrderExist($seat,$item = 'o.*'){
        $where = [
            ['oc.seat_id','=',$seat['seat_id']],
            ['o.pay_status','=',1],
            ['o.special_status','=',1],
            ['o.is_del','=',1],
        ];
        $order = $this->
            alias('o')
            ->leftJoin('ddt_offline_record oc','o.order_id = oc.order_id')
            ->where($where)
            ->field($item)
            ->order('o.order_time desc')
            ->find();
        return $order;
    }

////    处理线下订单插入数据
//    function placeofflineorder($user,$ids,$shop_id,$seat,$data){
//        $detailModel = new \app\common\model\OrderDetail();
//        $time = time();
//        $result = [
//            'code' => false,
//            'data' => [],
//        ];
////        var_dump($user);die;
//        $paydata = [
//            'products_amount' => $data['price']['products_amount'],
//            'coupon_amount' => $data['price']['coupon_amount'],
//            'express_fee' => $data['price']['express_fee'],
//            'order_amount' => $data['price']['order_amount'],
//            'pay_amount' => $data['price']['pay_amount'],
//            'points' => 0,
//            'growth_coin' => $data['price']['all_growth_coin'],
//        ];
//
//        $this->startTrans();
//        $paymentModel = new Payments();
//        $insertpayments = [
//            "user" => $user,
//            "data" => $data['price'],
//        ];
//        $payments_id = $paymentModel->insertpayments($insertpayments,"offline");
//        if($payments_id === false){
//            $paymentModel->rollback();
//            $this->setError(-1,'插入购买记录失败');
//            return $result;
//        }
//        $insertorder['data'] = $paydata;
//        $insertorder['shop_id'] = $data['list'][$shop_id]['shop_id'];
//        $insertorder['order_type'] = 5;
//        $insertorder['order_time'] = $time;
//        $insertorder['user_id'] = $user['user_id'];
//        $insertorder['address_id'] = 0;
//        $insertorder['receive_id'] = 0;
//        $insertorder['order_status'] = 1;
//        $insertorder['pay_status'] = 1;
//        $insertorder['payments_id'] = $payments_id;
//        $insertorder['remark'] = $data['remark'];
//        $orderid = $this->insertorder($insertorder);
//        if($orderid === false){
//            $this->rollback();
//            $this->setError(-1,'订单生成失败');
//            return $result;
//        }
//
//        $orModel = new OfflineRecord();
//        $or_rs = $orModel->InsertOfflineRecord($user,$orderid,$shop_id,$seat);
//        if($or_rs === false){
//            $this->rollback();
//            $this->setError(-1,$orModel->getError());
//            return $result;
//        }
//        $utype = $user['utype'] == 2 ?'mprice':'sprice';
//        $stockModel = new ProductStock();
//        $i = 0;
//        foreach($data['products'] as $value){
//            $insertdetail[$i]['user_id'] = $user['user_id'];
//            $insertdetail[$i]['order_id'] = $orderid;
//            $insertdetail[$i]['product_id'] = $value['product_id'];
//            $insertdetail[$i]['product_name'] = $value['product_name'];
//            $insertdetail[$i]['p_s_id'] = $value['p_s_id'];
//            $insertdetail[$i]['p_s_name'] = $value['p_s_name'];
//            $insertdetail[$i]['cover_url'] = $value['imageurl'];
//            $insertdetail[$i]['quantity'] = $value['quantity'];
//            $insertdetail[$i]['price'] = $value['price'];
//            $insertdetail[$i]['sale_price'] = $value[$utype];
//            $insertdetail[$i]['growth_coin'] = 0;
//            $insertdetail[$i]['amount'] = calculate([$insertdetail[$i]['sale_price'],$insertdetail[$i]['quantity']],'*',0);
//            $insertdetail[$i]['growth_coin_amount'] = 0;
//            $insertdetail[$i]['department_id'] = $value['department_id'];
//
//            $i += 1;
//
//            $reduce_rs = $stockModel->reducestock($value['product_id'],$value['p_s_id'],$value['quantity']);
////                var_dump($reduce_rs);die;
//            if($reduce_rs === false){
//                $paymentModel->rollback();
//                $this->setError(-1,'商品库存减少失败');
//                return $result;
//            }
//        }
//        $res = $detailModel->saveAll($insertdetail);
//        if($res === false){
//            $this->rollback();
//            $this->setError(-1,'订单商品信息记录失败');
//            return $result;
//        }
//
//        $this->commit();
//        $cartModel = new Cart();
//        $cartModel->delcart($user['user_id'],$ids);
//        $result['code'] = true;
//        $result['data'] = [
//            'orderid' => $orderid,
//            'paymentsid' => $payments_id,
//        ];
//        return $result;
//    }
//    处理线下订单插入数据
    function placeofflineorder($user,$ids,$data){
        $detailModel = new \app\common\model\OrderDetail();
        $time = time();
        $result = [
            'code' => false,
            'data' => [],
        ];
//        var_dump($user);die;
        $paydata = [
            'products_amount' => $data['price']['products_amount'],
            'coupon_amount' => $data['price']['coupon_amount'],
            'express_fee' => $data['price']['express_fee'],
            'order_amount' => $data['price']['order_amount'],
            'pay_amount' => $data['price']['pay_amount'],
            'points' => 0,
            'growth_coin' => $data['price']['all_growth_coin'],
        ];
//        var_dump($paydata);die;

        $this->startTrans();
        $paymentModel = new Payments();
        $insertpayments = [
            "user" => $user,
            "data" => $data['price'],
        ];
        $payments_id = $paymentModel->insertpayments($insertpayments,"offline");
        if($payments_id === false){
            $paymentModel->rollback();
            $this->setError(-1,'插入购买记录失败');
            return $result;
        }
        $insertorder['data'] = $paydata;
        $insertorder['shop_id'] = 0;
        $insertorder['order_type'] = 5;
        $insertorder['order_time'] = $time;
        $insertorder['user_id'] = $user['user_id'];
        $insertorder['address_id'] = 0;
        $insertorder['receive_id'] = 0;
        $insertorder['order_status'] = 1;
        $insertorder['pay_status'] = 1;
        $insertorder['payments_id'] = $payments_id;
        $insertorder['r_address'] = $data['r_address'];
        $insertorder['r_phone'] = $data['r_phone'];
        $insertorder['receive_name'] = $data['receive_name'];
        $insertorder['receive_time'] = $data['receive_time'];
        $orderid = $this->insertorder($insertorder);
        if($orderid === false){
            $this->rollback();
            $this->setError(-1,'订单生成失败');
            return $result;
        }
        $utype = $user['utype'] == 2 ?'mprice':'sprice';
        $i = 0;
        foreach($data['products'] as $value){
            $insertdetail[$i]['user_id'] = $user['user_id'];
            $insertdetail[$i]['order_id'] = $orderid;
            $insertdetail[$i]['product_id'] = $value['product_id'];
            $insertdetail[$i]['product_name'] = $value['product_name'];
            $insertdetail[$i]['product_describe'] = $value['describe'];
            $insertdetail[$i]['cover_url'] = $value['imageurl'];
            $insertdetail[$i]['quantity'] = $value['quantity'];
            $insertdetail[$i]['price'] = $value[$utype];
            $insertdetail[$i]['sale_price'] = $value[$utype];
            $insertdetail[$i]['growth_coin'] = 0;
            $insertdetail[$i]['amount'] = calculate([$insertdetail[$i]['sale_price'],$insertdetail[$i]['quantity']],'*',2);
            $insertdetail[$i]['growth_coin_amount'] = 0;
            $insertdetail[$i]['department_id'] = $value['department_id'];
            $insertdetail[$i]['add_time'] = $time;
            $insertdetail[$i]['update_time'] = $time;

            $i += 1;
        }
        $res = $detailModel->saveAll($insertdetail);
        if($res === false){
            $this->rollback();
            $this->setError(-1,'订单商品信息记录失败');
            return $result;
        }

        $this->commit();
        $cartModel = new Cart();
        $cartModel->delcart($user['user_id'],$ids);
        $result['code'] = true;
        $result['data'] = [
            'orderid' => $orderid,
            'paymentsid' => $payments_id,
        ];
        return $result;
    }

//    线下追加订单插入数据
    function addtoofflineorder($order,$user,$ids,$data){
//        var_dump($order);
        $detailModel = new OrderDetail();
        $result = [
            'code' => false,
            'data' => [],
        ];
//        var_dump($user);die;
        $this->startTrans();
        $paymentModel = new Payments();
        $payments_rs = $paymentModel->where('payments_id','=',$order['payments_id'])->setInc('amount',$data['price']['pay_amount']);
        if($payments_rs === false){
            $paymentModel->rollback();
            $this->setError(-1,'更新购买记录金额失败');
            return $result;
        }
        $order_update = [
            'products_amount' => calculate([$order['products_amount'],$data['price']['products_amount']],'+',2),
            'express_fee' => calculate([$order['express_fee'],$data['price']['express_fee']],'+',2),
            'order_amount' => calculate([$order['order_amount'],$data['price']['order_amount']],'+',2),
            'pay_amount' => calculate([$order['pay_amount'],$data['price']['pay_amount']],'+',2),
            'remarks' => empty($order['remarks'])?$data['remark']:(empty($data['remark'])?$order['remarks']:$data['remark']."、".$order['remarks']),
        ];
//        var_dump($order_update);die;
        $order_rs = $this->where('order_id','=',$order['order_id'])->update($order_update);
        if($order_rs === false){
            $this->rollback();
            $this->setError(-1,'订单数据更新失败');
            return $result;
        }

        $utype = $user['utype'] == 2 ?'mprice':'sprice';
        $stockModel = new ProductStock();
        foreach($data['products'] as $key => $value){
            $insertdetail[$key]['user_id'] = $user['user_id'];
            $insertdetail[$key]['order_id'] = $order['order_id'];
            $insertdetail[$key]['product_id'] = $value['product_id'];
            $insertdetail[$key]['product_name'] = $value['product_name'];
            $insertdetail[$key]['p_s_id'] = $value['p_s_id'];
            $insertdetail[$key]['p_s_name'] = $value['p_s_name'];
            $insertdetail[$key]['cover_url'] = $value['imageurl'];
            $insertdetail[$key]['quantity'] = $value['quantity'];
            $insertdetail[$key]['price'] = $value['price'];
            $insertdetail[$key]['sale_price'] = $value[$utype];
            $insertdetail[$key]['growth_coin'] = 0;
            $insertdetail[$key]['amount'] = calculate([$insertdetail[$key]['sale_price'],$insertdetail[$key]['quantity']],'*',0);
            $insertdetail[$key]['growth_coin_amount'] = 0;
            $insertdetail[$key]['department_id'] = $value['department_id'];

            $reduce_rs = $stockModel->reducestock($value['product_id'],$value['p_s_id'],$value['quantity']);
//                var_dump($reduce_rs);die;
            if($reduce_rs === false){
                $paymentModel->rollback();
                $this->setError(-1,'商品库存减少失败');
                return $result;
            }
        }
        $res = $detailModel->saveAll($insertdetail);
        if($res === false){
            $this->rollback();
            $this->setError(-1,'订单商品信息记录失败');
            return $result;
        }

        $this->commit();
        $cartModel = new Cart();
        $cartModel->delcart($user['user_id'],$ids);
        $result['code'] = true;
        $result['data'] = [
            'orderid' => $order['order_id'],
            'paymentsid' => $order['payments_id'],
        ];
        return $result;
    }

//    后台获取线下订单列表
    function AdminGetOfflineOrderList($cond,$orderby = 'order_id desc',$limit = 10){

		if(!empty($cond['shop_name'])){
			$where[] = ['s.shop_name','like','%'.$cond['shop_name'].'%'];
		}

		if(!empty($cond['seat_num'])){
			$where[] = ['ss.seat_num','like','%'.$cond['seat_num'].'%'];
		}

        if(!empty($cond['user_id'])){
            $where[] = ['user_id','=', $cond['user_id']];
        }
        if(isset($cond['shop_id'])){
            $where[] = ['o.shop_id','=', $cond['shop_id']];
        }
        if(!empty($cond['order_id'])){
            $where[] = ['o.order_id','=', $cond['order_id']];
        }

        if(!empty($cond['order_type'])){
            $where[] = ['o.order_type', 'in', $cond['order_type']];
        }
        if(!empty($cond['order_status'])){
            $where[] = ['o.order_status', '=',$cond['order_status']];
        } else {
            $where[] = ['o.order_status', 'in','2,3,4,6,7'];
        }
        if(!empty($cond['pay_status'])){
            $where[] = ['o.pay_status', '=', $cond['pay_status']];
        }
        if(!empty($cond['time'])){
            $array = explode(' - ',input('get.time'));
            $start = strtotime($array[0]." 00:00:00");
            if($array[0] == $array[1]){
                $end = strtotime($array[0]." 23:59:59");
            } else {
                $end = strtotime($array[1]." 00:00:00");
            }
            $where[] = ['o.order_time','between',[$start,$end]];
        }
        $where[] = ['o.is_del','=',1];
        $with = [
            'orderDetails',
        ];

        $data = $this
			->alias('o')
            ->field('o.*,s.shop_name,ss.seat_num')
            ->with($with)
            ->where($where)
			->leftJoin([
				['ddt_shops s','o.shop_id=s.shop_id'],
				['ddt_offline_record or','o.order_id=or.order_id'],
				['ddt_shops_seat ss','or.seat_id=ss.seat_id'],
			])
            ->order($orderby)
            ->paginate($limit)
            ->each(function($query){
                if(!empty($query['offline_records'])){
                    $query['offline_records']['seat_info'] = json_decode($query['offline_records']['seat_info'],true);
                    $query['offline_records'] = $query['offline_records']->toArray();
                }
                if(!empty($query['order_details'])){
                    $details = $query['order_details']->toArray();
                    $query['order_details'] = $details;
                    $numbers = array_column($details,'quantity');
                    $query['total'] = array_sum($numbers);
                }
                return $query;
            });
//        echo $this->getLastSql();
        return $data;
    }

//    后台导出线下订单数据
    function AdminImportOfflineOrderList($cond,$item = '*',$orderby = 'order_id desc'){

        if(!empty($cond['user_id'])){
            $where[] = ['user_id','=', $cond['user_id']];
        }
        if(isset($cond['shop_id'])){
            $where[] = ['shop_id','=', $cond['shop_id']];
        }
        if(!empty($cond['order_id'])){
            $where[] = ['order_id','=', $cond['order_id']];
        }

        if(!empty($cond['order_type'])){
            $where[] = ['order_type', 'in', $cond['order_type']];
        }
        if(!empty($cond['order_status'])){
            $where[] = ['order_status', '=', $cond['order_status']];
        }
        if(!empty($cond['pay_status'])){
            $where[] = ['pay_status', '=', $cond['pay_status']];
        }
        if(!empty($cond['time'])){
            $array = explode(' - ',input('get.time'));
            $start = strtotime($array[0]." 00:00:00");
            if($array[0] == $array[1]){
                $end = strtotime($array[0]." 23:59:59");
            } else {
                $end = strtotime($array[1]." 00:00:00");
            }
            $where[] = ['order_time','between',[$start,$end]];
        }
        $where[] = ['is_del','=',1];
        $with = [
            'getShops' => function($query) {
                $query->field('shop_id,shop_name,shop_phone,address,province,city,area,imagesurl');
            },
            'orderDetails',
            'offlineRecords' => function($query) {
                $query->field('off_r_id,order_id,seat_id,access_code,seat_info');
            }
        ];

        $data = $this
            ->field($item)
            ->with($with)
            ->where($where)
            ->order($orderby)
            ->select()
            ->each(function($query){
                if(!empty($query['offline_records'])){
                    $query['offline_records']['seat_info'] = json_decode($query['offline_records']['seat_info'],true);
                    $query['offline_records'] = $query['offline_records']->toArray();
                }
                if(!empty($query['order_details'])){
                    $details = $query['order_details']->toArray();
                    $query['order_details'] = $details;
                    $numbers = array_column($details,'quantity');
                    $query['total'] = array_sum($numbers);
                }
                return $query;
            });
//        echo $this->getLastSql();
        return $data;
    }
}